<?php

namespace App\Http\Middleware;

use App\Models\Permission;
use App\Models\Role;
use App\Services\Service\Helper;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class AdminPermissionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        /**
         * 判断是否为不用授权管理员(配置角色)
         */
        if (!Role::isAdmin()) {
            $route_name = Route::currentRouteName();
            $cache_key = $route_name;
            $wheres['where'][] = ['controller', '!=', 'sysmenu'];
            $permissions = Permission::getCache($wheres, ['pid' => 'asc', 'sort' => 'asc']);
            if (!isset($permissions[$cache_key])) {
                return Helper::errorHandle($request, '功能权限配置未发现', 'user', 404);
            } else {
                $permission_id = $permissions[$cache_key]['id'];
                $permission = Permission::find($permission_id);
                if (!Auth::user()->hasPermission($permission)) {
                    return Helper::errorHandle($request, '你没有该功能的操作权限', 'user');
                }
            }
        }
        return $next($request);
    }
}
